<?php
class Mageex_AdvanceSeo_Model_Submit{
	
	public function submit($sitemapId) {
		
		if (!Mage::helper('advanceseo/sitemap')->isEnabled()) {
			throw new Exception("Sitemap Submit Extension disabled - not submiting sitemap.");
			return;
		}
		
		$sitemap = Mage::getModel('sitemap/sitemap');
        $sitemap->load($sitemapId);
        
        if(!$sitemap->getId()) {
        	throw new Exception("Site map could not be found with ID: " . $sitemapId);
        }
     
        $fileName = preg_replace('/^\//', '', $sitemap->getSitemapPath() . $sitemap->getSitemapFilename());
        $url = Mage::app()
        	->getStore($sitemap->getStoreId())
        	->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK) . $fileName;
		
		$typeSubmit = Mage::helper('advanceseo/sitemap')->getTypeSubmit();
		
		//If type: sitemap index
		
		if($typeSubmit=='index'){
			$fileName 	= preg_replace('/^\//', '',$sitemap->getSitemapPath().'sitemapindex-'.$sitemap->getSitemapFilename());
			$url 		= Mage::app()
								->getStore($sitemap->getStoreId())
								->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK) . $fileName;
			if (file_exists(BP . DS . $fileName)) {
				
				$msg = "";
				
				//ping google
				if($this->_pingGoogle($url)) {
					$msg = $msg . "Pinged Google successfully<br/>";
				} else {
					$msg = $msg . "Failed to ping Google.<br/>";
				}
				
				//ping yahoo
				if ($yahooApiKey = Mage::helper('advanceseo/sitemap')->getYahooKey()) {
					
					if($this->_pingYahoo($url, $yahooApiKey)) {
						$msg = $msg . "Pinged Yahoo successfully<br/>";
					} else {
						$msg = $msg . "Failed to ping Yahoo.<br/>";
					}
					
				} else {
					$msg = $msg . "Skipping Yahoo. (You need to provide an API key to submit your sitemap to Yahoo)<br/>";
				}
				
				//ping ask
				if($this->_pingAsk($url)) {
					$msg = $msg . "Pinged Ask successfully<br/>";
				} else {
					$msg = $msg . "Failed to ping Ask.<br/>";
				}
				
				
				//ping bing
				if($this->_pingBing($url)) {
					$msg = $msg . "Pinged Bing successfully<br/>";
				} else {
					$msg = $msg . "Failed to ping Bing.<br/>";
				}
				
				return "Sitemap submit for url: " . $url . " complete.<br/>Results are: <br/>" . $msg;
				
			} else {
				throw new Exception("Site map could not be found in required location: " . BP . DS . $fileName.'. Are you Sure sitemap generated ?');
			}
		}
        //If type: sitemap normal
		if($typeSubmit=='sitemap'){
			$dir 			= BP . DS .preg_replace('/^\//', '',$sitemap->getSitemapPath());
			$parentName 	= str_replace('.xml', '', $sitemap->getSitemapFilename());
			$arrFileName 	= Mage::helper('advanceseo')->getFileNameToArr($dir, 'sitemapindex', $parentName, false);
			$pingGoogle 	= false;
			$pingYahoo 		= false;
			$pingBing 		= false;
			$pingAsk 		= false;
			$msg			= '';
			$yahooApiKey = Mage::helper('advanceseo/sitemap')->getYahooKey();
			foreach ($arrFileName as $file) {
				$fileName	= preg_replace('/^\//', '',$sitemap->getSitemapPath()). $file;
				$url		= Mage::app()
									->getStore($sitemap->getStoreId())
									->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK) .$fileName;
				if (file_exists(BP . DS . $fileName)) {	
					if($this->_pingGoogle($url)){
						$pingGoogle = true;
					}	
					if($yahooApiKey){
						if($this->_pingYahoo($url,$yahooApiKey)){
							$pingYahoo = true;
						}
					}
					if($this->_pingBing($url)){
						$pingBing = true;
					}
					if($this->_pingAsk($url)){
						$pingAsk = true;
					}
				}
			}
			if($pingGoogle==true){
				$msg .= "Pinged Google successfully<br/>";
			}else{
				$msg .= "Failed to ping Google<br/>";
			}
			if(!$yahooApiKey){
				$msg .= "Skipping Yahoo. (You need to provide an API key to submit your sitemap to Yahoo)<br/>";
			}
			if($pingYahoo==true){
				$msg .= "Pinged Yahoo successfully<br/>";
			}else{
				$msg .= "Failed to ping Yahoo<br/>";
			}
			if($pingBing==true){
				$msg .= "Pinged Bing successfully<br/>";
			}else{
				$msg .= "Failed to ping Bing<br/>";
			}
			if($pingAsk==true){
				$msg .= "Pinged Ask successfully<br/>";
			}else{
				$msg .= "Failed to ping Ask<br/>";
			}
			return "Results submit sitemap are: <br/>" . $msg;
		}
		//TODO: Add more search engines
	}
	
	protected function _pingGoogle($url) {
		$ping="http://www.google.com/webmasters/sitemaps/ping?sitemap=" . urlencode($url);
		return $this->_makeRequest($ping);
	}
	
	protected function _pingYahoo($url, $yahooApiKey) {
		$ping="http://search.yahooapis.com/SiteExplorerService/V1/updateNotification?url=" . 
				urlencode($url) . "&appid=" . $yahooApiKey;	
		return $this->_makeRequest($ping);
	}
	
	protected function _pingBing($url) {
			$ping="http://www.bing.com/webmaster/ping.aspx?siteMap=" . urlencode($url);
		return $this->_makeRequest($ping);
	}
	
	protected function _pingAsk($url) {
		$ping="http://submissions.ask.com/ping?sitemap=" . urlencode($url);
		return $this->_makeRequest($ping);
	}
	
	
	protected function _makeRequest($ping) {
		
		$curl = new Varien_Http_Adapter_Curl();
        $curl->setConfig(array(
            'timeout'   => 20
        ));
        
        $curl->write(Zend_Http_Client::GET, $ping, '1.1');
        $data = $curl->read();
        
        if ($data === false) {
            return false;
        }
       
        if ($curl->getInfo(CURLINFO_HTTP_CODE) == 200) {
	       // Mage::log($data); // uncomment to debug raw submission response
	        return $data;
        } else {
	        Mage::log("Submission to: " . $ping . " failed, HTTP response code was not 200");
	        return false;
        }
        
        //TODO: handle timeout?
		
	}
	
}